<?php
/*
 * @Author: kaleozhou
 * @Email: kaleo1990@hotmail.com
 * @Blog: www.kaleozhou.top
 * @Date: 2021-05-20 22:12:03
 * @LastEditors: kaleozhou
 * @LastEditTime: 2021-05-22 16:35:30
 * @Description: content
 */

namespace Encore\UploadFileCos;

use Encore\Admin\Form\Field;

class UploadFileCosField extends Field
{

    protected $group = 'file';
    protected $multiple = 'false';
    // 默认文件类型
    protected $accept = '*';
    public $view = 'uploadfilecos::index';
    public function group($group)
    {
        $this->group = $group;
        return $this;
    }
    // 是否多文件
    public function multiple($multiple)
    {
        $this->multiple = $multiple;
        return $this;
    }
    //接收文件的类型
    public function accept($accept)
    {
        $this->accept = $accept;
        return $this;
    }
    public function render()
    {
        $name = $this->formatName($this->column);
        $route_prefix = config('admin.route.prefix');
        // 请求用到的参数
        $bucket = config('filesystems.disks.cosv5.bucket');
        $region = config('filesystems.disks.cosv5.region');
        $this->script = <<<SRC
        $('#{$name}-resource').bootstrapFileInput();
        document.getElementById('{$name}-resource').setAttribute('accept','{$this->accept}');
        var Bucket = '{$bucket}';
        var Region = '{$region}';
        var protocol = location.protocol === 'https:' ? 'https:' : 'http:';
        var prefix = protocol + '//' + Bucket + '.cos.' + Region + '.myqcloud.com/';
        var output= $('#{$name}-output');
        var progressbar=$('#{$name}-progressbar');
        var savedpath=$('#{$name}-savedpath');
        //删除附件
        $('.{$name}-deleteFile').click(function(){
            var item=$(this).attr('value');
            var savedpath= document.getElementById('{$name}-savedpath');
            var saved_array=savedpath.value.split(',');
            var new_saved_str='';
            for (i=0;i<saved_array.length ;i++ ) 
            { 
                if(saved_array[i]!=item){
                    new_saved_str=new_saved_str?new_saved_str+','+saved_array[i]:saved_array[i];
                }
            }
            savedpath.value=new_saved_str;
            $(this).hide();
           });
        document.getElementById('{$name}-hint').hidden= !{$this->multiple};

        // 对更多字符编码的 url encode 格式
          var camSafeUrlEncode = function (str) {
              return encodeURIComponent(str)
                  .replace(/!/g, '%21')
                  .replace(/'/g, '%27')
                  .replace(/\(/g, '%28')
                  .replace(/\)/g, '%29')
                  .replace(/\*/g, '%2A');
          };
          // 计算签名
          var getAuthorization = function (options, callback) {
              // var url = 'http://127.0.0.1:3000/sts-auth';
              var url = "/{$route_prefix}/uploadfilecos";
              var xhr = new XMLHttpRequest();
              xhr.open('GET', url, true);
              xhr.onload = function (e) {
                  var credentials;
                  try {
                      credentials = (new Function('return ' + xhr.responseText))().credentials;
                  } catch (e) {}
                  if (credentials) {
                      callback(null, {
                          SecurityToken: credentials.sessionToken,
                          Authorization: CosAuth({
                              SecretId: credentials.tmpSecretId,
                              SecretKey: credentials.tmpSecretKey,
                              Method: options.Method,
                              Pathname: options.Pathname,
                          })
                      });
                  } else {
                      console.error(xhr.responseText);
                      callback('获取签名出错');
                  }
              };
              xhr.onerror = function (e) {
                  callback('获取签名出错');
              };
              xhr.send();
          };
          // 上传文件
          var uploadFile = function (file, callback,type) {

              var Key = '{$this->group}'+'/' + file.name; // 这里指定上传目录和文件名
              getAuthorization({Method: 'PUT', Pathname: '/' + Key}, function (err, info) {
  
                  if (err) {
                      alert(err);
                      return;
                  }
                  var auth = info.Authorization;
                  var SecurityToken = info.SecurityToken;
                  var url = prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/');
                  var xhr = new XMLHttpRequest();
                  xhr.open('PUT', url, true);
                  xhr.setRequestHeader('Authorization', auth);
                  SecurityToken && xhr.setRequestHeader('x-cos-security-token', SecurityToken);
                  xhr.upload.onprogress = function (e) {
                      console.log('上传进度 ' + (Math.round(e.loaded / e.total * 10000) / 100) + '%');
                      progressbar.css('width', (Math.round(e.loaded / e.total * 10000) / 100) + '%');
                    };
                  xhr.onload = function () {
                      if (xhr.status === 200 || xhr.status === 206) {
                          var ETag = xhr.getResponseHeader('etag');
                          callback(null, {url: url, ETag: ETag});
                      } else {
                          callback('文件 ' + Key + ' 上传失败，状态码：' + xhr.status);
                      }
                  };
                  xhr.onerror = function () {
                      callback('文件 ' + Key + ' 上传失败，请检查是否没配置 CORS 跨域规则');
                  };
                  xhr.send(file);
              });
          };

      
        // 监听选文件
        document.getElementById('{$name}-resource').onchange = function () {

            var file = this.files[0];
            if (!file) return;
            file && uploadFile(file, function (err, data) {
                console.log(err || data);
                if('{$this->multiple}'=='true'){
                    if(document.getElementById('{$name}-savedpath').value){
                        document.getElementById('{$name}-output').innerText = err ? err :document.getElementById('{$name}-output').innerText+ file.name +'√上传成功\\n';
                        document.getElementById('{$name}-savedpath').value=err ? '' :document.getElementById('{$name}-savedpath').value+','+(data.url);
                    }
                    else{
                        document.getElementById('{$name}-output').innerText = err ? err : file.name+'√上传成功\\n';
                        document.getElementById('{$name}-savedpath').value=err ? '' :(data.url);
                    }
                }else{
                    document.getElementById('{$name}-output').innerText = err ? err : file.name+'√上传成功\\n';
                    document.getElementById('{$name}-savedpath').value=err ? '' :(data.url);
                }
            },file);
        };
SRC;
        return parent::render();
    }
}
